<?php
namespace app\common\model;

use org\util\TreeUtil;
use think\facade\Cache;

class DeptModel extends BaseModel
{
    protected $name = 'dept';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 获取最顶级部门
     * @return mixed
     * @throws \Exception
     */
    public function getTopDept(){
        $list = $this->getList();
        $list = array_values($list);
        return $list[0];
    }
    /**
     * 获取缓存数据
     * @return mixed
     * @throws \Exception
     */
    public function getList(){
        if(!Cache::has($this->getCacheKey())){
            $this->updateCache();
        }
        $list = Cache::get($this->getCacheKey());
        return $list;
    }
    /**
     * 获取树型列表
     */
    public function getTreeList(){
        $list = $this->getList();
        $list = array_values($list);
        $treeList = TreeUtil::channelLevel($list,0);
        return $treeList;
    }

    /**
     * 获取部门信息
     * @param $map
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getInfo($map){
        $info = $this->where($map)->find();
        $list = $this->getList();
        $deptInfo = $list[$info['id']];
        return $deptInfo;
    }
    /**
     * 缓存数据
     * @return bool
     * @throws \Exception
     * 站点ID 行业ID
     //总管理 0 0
     //代理商 0 >0
     //店铺 >0 >0
     */
    public function updateCache(){
        try{
            $loginInfo = $this->getLoginInfo();
            $list = $this->where('site_id',$loginInfo['site_id'])->where('trade_id',$loginInfo['trade_id'])
                                                                 ->order('show_order asc')->select();
            $list = $list->isEmpty()?[]:$list->toArray();
            $list = TreeUtil::tree($list,'name'); //转换树型
            $cache=[];
            foreach($list as $k=>$v){
                //取所有下级，包含当前级
                $ids=$v['id']; //当前ID
                $hasChild = 0; //默认无下级
                $v['next_level']=[]; //下级分类
                $child = TreeUtil::channelList($list,$v['id']); //当前ID的所有下级
                $dataView = array_column($child,'id');
                if(!empty($dataView)){
                    $ids.=','.implode(',',$dataView);
                    $hasChild = 1;
                    foreach($child as $kk=>$vv){
                        if($vv['pid']==$v['id']) $v['next_level'][]=$vv;
                    }
                }
                $v['data_view'] = $ids;
                $v['has_child'] = $hasChild;
                //取所有上级
                $parents = array_reverse(TreeUtil::parentChannel($list, $v['id']));
                $path = array_column($parents,'id');
                $fullName = array_column($parents,'name');
                $v['path'] = implode(',',$path);
                $v['full_name'] = implode(',',$fullName);
                $cache[$v['id']] = $v;
            }
            Cache::set($this->getCacheKey(),$cache);
        }catch (\Exception $e){
            exception($e->getMessage());
        }
        return true;
    }

    /**
     * 删除部门
     * @param $id
     */
    public function delData($id) {
        $list = $this->getList();
        $deptInfo = $list[$id];
        if($deptInfo['pid']==0) exception('根部门不允许删除！');
        if($deptInfo['has_child']==1) exception('存在下级部门，不允许删除！');
        if(AdminAccessModel::where('dept_id',$id)->find()){
            exception('部门存在员工不允许删除');
        }
        $this->where('id',$id)->delete();
    }

    /**
     * 缓存标识
     * @return string
     */
    public function getCacheKey(){
        $loginInfo = $this->getLoginInfo();
        return 'dept_'.$loginInfo['site_id'].'_'.$loginInfo['trade_id'];
    }
}